package com.ccy.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import com.ccy.utils.IoUtils;
import com.ccy.utils.Log;

public class SocketTest {

	private static final String HOST = "www.baidu.com";
	
	public static void main(String[] args) {
		Socket socket = null;
		BufferedWriter fileOut = null;
		try {
			// connect
			Log.i("pre socket");
			socket = new Socket(HOST, 80);
			Log.i("socket created");
			// int trafficClass = socket.getTrafficClass();
			// Log.i("create " + socket + ", trafficClass = " + trafficClass);
			
			InputStream socketIn = socket.getInputStream();
			BufferedReader in = new BufferedReader(new InputStreamReader(socketIn));
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

			// File
			fileOut = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("D:\\baidu.html"))));
			
			Log.i("io create");

			out.println("GET /index.html HTTP/1.1");
			out.println("Host: " + HOST + ":80");
			out.println("Connection: close");
			out.println();
			Log.i("send http request");

			boolean loop = true;
			while (loop) {
				// System.err.println(socketIn.getClass().getName() + " available = " + socketIn.available());
				if (in.ready()) {
					loop = false;
					
					int len = -1;
					int count = 0;
					System.err.println("count = " + count + " " + socketIn.getClass().getName() + " available = " + socketIn.available());
					char[] buffer = new char[1024];
					while ((len = in.read(buffer)) != -1) {
						count++;
						fileOut.write(buffer, 0, len);
						System.err.println("count = " + count + " " + socketIn.getClass().getName() + " available = " + socketIn.available());
					}
				} 
				
				// not ready
				else {
					Log.e("in not ready");
					Thread.sleep(50);
				}
			}
//			fileOut = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("D:\\baidu.html_2"))));
//			doService(fileOut, socketIn, in, out);
		} catch (UnknownHostException e) {
			Log.e("unable to connect baidu", e);
		} catch (IOException e) {
			Log.e("IOE", e);
		} catch (InterruptedException e) {
			Log.e("InterruptedException", e);
		} finally {
			IoUtils.closeSilently(socket); // in/out 随之关闭
			IoUtils.closeSilently(fileOut);
		}
	}
}
